package com.yupi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.yupi.project.annotation.AuthCheck;
import com.yupi.project.bizmq.BIMessageProducer;
import com.yupi.project.common.BaseResponse;
import com.yupi.project.common.DeleteRequest;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.common.ResultUtils;
import com.yupi.project.config.ThreadPoolConfig;
import com.yupi.project.constant.UserConstant;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.mapper.ChartMapper;
import com.yupi.project.model.dto.Chart.ChartAddRequest;
import com.yupi.project.model.dto.post.GenChartRequest;
import com.yupi.project.model.entity.Chart;
import com.yupi.project.model.entity.User;

import com.yupi.project.service.ChartService;
import com.yupi.project.service.UserService;
import com.yupi.project.service.impl.AIChart;
import com.yupi.project.service.impl.AIManager;
import com.yupi.project.service.impl.RedissonManager;
import com.yupi.project.service.impl.ZhiPuAIClient;
import com.yupi.project.utils.ExcelUtils;
import com.yupi.yucongming.dev.model.DevChatResponse;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/Chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService ChartService;
    @Resource
    private UserService userService;
    @Resource
    private AIChart aiChart;
    // region 增删改查
    @Resource
    private RedissonManager redissonManager;
    //星火AI模型调用
    @Resource
    private AIManager aiManager;
    @Resource
    private ThreadPoolConfig threadPoolConfig;
    @Resource
    private ZhiPuAIClient zhiPuAIClient;
    @Resource
    private BIMessageProducer biMessageProducer;
    @Resource
    private ChartMapper chartMapper;
    @PostMapping("/genChartSyn")
    public BaseResponse<String> genChartbyAISyn(@RequestPart("file") MultipartFile multipartFile,
                                                GenChartRequest genChartRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        //Long userId = loginUser.getId();

        ThreadPoolExecutor executor = threadPoolConfig.getExecutor();
        String name = genChartRequest.getName();
        String goal = genChartRequest.getGoal();
        String chatType = genChartRequest.getChatType();
        //校验逻辑
        //文件校验
        //1.校验文件的大小
        long size = multipartFile.getSize();
        long MAX_SIZE = 1024 * 1024L;
        if (size>MAX_SIZE){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件上传过大");
        }
        //2.校验文件的后缀
        String filename = multipartFile.getOriginalFilename();
        List<String> backList = Arrays.asList("xlsx", "xls");
        String fileSuffix = "";
        if (filename != null) {
            fileSuffix = filename.replaceAll(".*\\.(.*)", "$1");
            if (!backList.contains(fileSuffix)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件格式错误");
            }
        }
        //设置限流
        //redissonManager.tryAcquire("genChartbyAI:"+String.valueOf(loginUser.getId()));
        //设置提示词
        StringBuilder prompt = new StringBuilder();
        prompt.append("你是一个数据分析师和前端开发专家，接下来我会按照以下固定格式给你提供内容").append("\n");
        prompt.append("分析目标:").append(goal).append("\n");
        //得到压缩后的数据
        String csvResult = ExcelUtils.excelToCsv(multipartFile);
        //System.out.println("压缩后的数据："+csvResult);
        prompt.append("分析数据:").append(csvResult);
        prompt.append("输出格式（不要输出多余内容）:").append("\n");
        prompt.append("【【【【【").append("\n");
        prompt.append("option = {\n" +
                "  xAxis: {\n" +
                "    type: ',\n" +
                "    data: ['', '', '', '', '', ...]\n" +
                "  },\n" +
                "  yAxis: {\n" +
                "    type: 'value'\n" +
                "  },\n" +
                "  series: [\n" +
                "    {\n" +
                "      data: [, , , , , , ....],\n" +
                "      type: 'line'\n" +
                "    }\n" +
                "  ]\n" +
                "};").append("\n");
        prompt.append("【【【【【").append("\n");
        prompt.append("分析结论:");
        //System.out.println("提示词:"+prompt.toString());
        //调用AI模型
        //String result = aiManager.sendMsgToXingHuo(false, prompt.toString());
        String result = zhiPuAIClient.callAI(prompt.toString());
        System.out.println(result);
        String[] split = result.split("【【【【【");
        String chartCode = "";
        String genResult = "";
        if (split[1] != null){
            chartCode = split[1];
            System.out.println(split[1].trim());
        }
        if (split[2] != null){
            genResult = split[2];
            //System.out.println(split[2].trim());
        }
        //存储再从数据库中
        Chart chart = new Chart();
        chart.setName("");
        chart.setGoal(goal);
        chart.setChartData(csvResult);
        chart.setChatType("");
        chart.setGenChart(chartCode);
        chart.setGenResult(genResult);
        chart.setUserId(null);
        boolean save = ChartService.save(chart);
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"数据库保存失败");
        }
        Long id = chart.getId();
        String chartName = "chart_" + id;
        Map<String, Object> map = new HashMap<>();
        String[] dataSplit = csvResult.split("\n");
        String columnsSplit = dataSplit[0];
        String[] columns = columnsSplit.split(",");
        map.put("tableName", chartName);
        map.put("columns", columns);
        Boolean table = chartMapper.createTable(map);
        if (!table){
            ResultUtils.error(ErrorCode.OPERATION_ERROR,"建表失败");
        }
        List<Map<String, Object>> dataList = new ArrayList<>();
        for (int i = 1; i < dataSplit.length; i++) {
            Map<String, Object> row = new HashMap<>();
            int k = 0;
            String s = dataSplit[i];
            String[] strings = s.split(",");
            for (int j = 0; j < columns.length; j++) {
                row.put(columns[j], strings[k]);
                k++;
            }
            dataList.add(row);
        }
        Boolean data = chartMapper.insertData(chartName, dataList);
        if (!data){
            ResultUtils.error(ErrorCode.OPERATION_ERROR,"数据插入失败");
        }
        return ResultUtils.success(result);
    }

    @PostMapping("/genChartAsy")
    public BaseResponse<String> genChartbyAIAsy(@RequestPart("file") MultipartFile multipartFile,
                                                GenChartRequest genChartRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        //Long userId = loginUser.getId();

        ThreadPoolExecutor executor = threadPoolConfig.getExecutor();
        String name = genChartRequest.getName();
        String goal = genChartRequest.getGoal();
        String chatType = genChartRequest.getChatType();
        //校验逻辑

        //文件校验
        //1.校验文件的大小
        long size = multipartFile.getSize();
        long MAX_SIZE = 1024 * 1024L;
        if (size>MAX_SIZE){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件上传过大");
        }
        //2.校验文件的后缀
        String filename = multipartFile.getOriginalFilename();
        List<String> backList = Arrays.asList("xlsx", "xls");
        String fileSuffix = "";
        if (filename != null) {
            fileSuffix = filename.replaceAll(".*\\.(.*)", "$1");
            if (!backList.contains(fileSuffix)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件格式错误");
            }
        }
        //设置限流
        //redissonManager.tryAcquire("genChartbyAI:"+String.valueOf(loginUser.getId()));
        //设置提示词
        StringBuilder prompt = new StringBuilder();
        prompt.append("你是一个数据分析师和前端开发专家，接下来我会按照以下固定格式给你提供内容").append("\n");
        prompt.append("分析目标:").append(goal).append("\n");
        //得到压缩后的数据
        String csvResult = ExcelUtils.excelToCsv(multipartFile);
        //System.out.println("压缩后的数据："+csvResult);
        prompt.append("分析数据:").append(csvResult);
        prompt.append("输出格式（不要输出多余内容）:").append("\n");
        prompt.append("【【【【【").append("\n");
        prompt.append("option = {\n" +
                "  xAxis: {\n" +
                "    type: ',\n" +
                "    data: ['', '', '', '', '', ...]\n" +
                "  },\n" +
                "  yAxis: {\n" +
                "    type: 'value'\n" +
                "  },\n" +
                "  series: [\n" +
                "    {\n" +
                "      data: [, , , , , , ....],\n" +
                "      type: 'line'\n" +
                "    }\n" +
                "  ]\n" +
                "};").append("\n");
        prompt.append("【【【【【").append("\n");
        prompt.append("分析结论:");
        //System.out.println("提示词:"+prompt.toString());
        //创建异步任务
        CompletableFuture<String> future =CompletableFuture.supplyAsync(() -> {
            //String result = aiManager.sendMsgToXingHuo(false, prompt.toString());
            //AI模型调用
            String result = zhiPuAIClient.callAI(prompt.toString());
            String[] split = result.split("【【【【【");
            String chartCode = "";
            String genResult = "";
            if (split[1] != null){
                chartCode = split[1];
                System.out.println(split[1].trim());
            }
            if (split[2] != null){
                genResult = split[2];
                System.out.println(split[2].trim());
            }
            //存储再从数据库中
            Chart chart = new Chart();
            chart.setName("");
            chart.setGoal(goal);
            chart.setChartData(csvResult);
            chart.setChatType("");
            chart.setGenChart(chartCode);
            chart.setGenResult(genResult);
            chart.setUserId(null);
            boolean save = ChartService.save(chart);
            if (!save) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"数据库保存失败");
            }
            return result;
        },executor);
        String result = future.join();
        return ResultUtils.success(result);
    }

    @PostMapping("/genChartMQ")
    public BaseResponse<String> genChartbyAIMQ(@RequestPart("file") MultipartFile multipartFile,
                                               GenChartRequest genChartRequest, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        //Long userId = loginUser.getId();

        ThreadPoolExecutor executor = threadPoolConfig.getExecutor();
        String name = genChartRequest.getName();
        String goal = genChartRequest.getGoal();
        String chatType = genChartRequest.getChatType();
        //校验逻辑

        //文件校验
        //1.校验文件的大小
        long size = multipartFile.getSize();
        long MAX_SIZE = 1024 * 1024L;
        if (size>MAX_SIZE){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件上传过大");
        }
        //2.校验文件的后缀
        String filename = multipartFile.getOriginalFilename();
        List<String> backList = Arrays.asList("xlsx", "xls");
        String fileSuffix = "";
        if (filename != null) {
            fileSuffix = filename.replaceAll(".*\\.(.*)", "$1");
            if (!backList.contains(fileSuffix)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件格式错误");
            }
        }
        //设置限流
        //redissonManager.tryAcquire("genChartbyAI:"+String.valueOf(loginUser.getId()));
        //设置提示词
        StringBuilder prompt = new StringBuilder();
        prompt.append("你是一个数据分析师和前端开发专家，接下来我会按照以下固定格式给你提供内容").append("\n");
        prompt.append("分析目标:").append(goal).append("\n");
        //得到压缩后的数据
        String csvResult = ExcelUtils.excelToCsv(multipartFile);
        //System.out.println("压缩后的数据："+csvResult);
        prompt.append("分析数据:").append(csvResult);
        prompt.append("输出格式（不要输出多余内容）:").append("\n");
        prompt.append("【【【【【").append("\n");
        prompt.append("option = {\n" +
                "  xAxis: {\n" +
                "    type: ',\n" +
                "    data: ['', '', '', '', '', ...]\n" +
                "  },\n" +
                "  yAxis: {\n" +
                "    type: 'value'\n" +
                "  },\n" +
                "  series: [\n" +
                "    {\n" +
                "      data: [, , , , , , ....],\n" +
                "      type: 'line'\n" +
                "    }\n" +
                "  ]\n" +
                "};").append("\n");
        prompt.append("【【【【【").append("\n");
        prompt.append("分析结论:");
        //
        biMessageProducer.sendMessage(prompt.toString());

        return ResultUtils.success("");
    }


    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = ChartService.getById(id);

        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = ChartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param ChartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody com.yupi.project.model.dto.Chart.ChartUpdateRequest ChartUpdateRequest) {
        if (ChartUpdateRequest == null || ChartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart Chart = new Chart();
        BeanUtils.copyProperties(ChartUpdateRequest, Chart);

        // 参数校验
        //ChartService.validChart(Chart, false);
        long id = ChartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = ChartService.getById(id);

        boolean result = ChartService.updateById(Chart);
        return ResultUtils.success(result);
    }




    /**
     * 编辑（用户）
     *
     * @param ChartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody com.yupi.project.model.dto.Chart.ChartEditRequest ChartEditRequest, HttpServletRequest request) {
        if (ChartEditRequest == null || ChartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart Chart = new Chart();
        BeanUtils.copyProperties(ChartEditRequest, Chart);

        // 参数校验
        //ChartService.validChart(Chart, false);
        User loginUser = userService.getLoginUser(request);
        long id = ChartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = ChartService.getById(id);

        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = ChartService.updateById(Chart);
        return ResultUtils.success(result);
    }


    public QueryWrapper<Chart> getQueryWrapper(com.yupi.project.model.dto.Chart.ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        Long id = chartQueryRequest.getId();
        String goal = chartQueryRequest.getGoal();
        String chatType = chartQueryRequest.getChatType();
        Long userId = chartQueryRequest.getUserId();
        String name = chartQueryRequest.getName();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        queryWrapper.eq(id !=null && id > 0,"id",id);
        queryWrapper.eq(StringUtils.isNotBlank(goal),"goal",goal);
        queryWrapper.eq(StringUtils.isNotBlank(chatType),"chartType",chatType);
        queryWrapper.eq(userId > 0,"userId",userId);
        queryWrapper.like(StringUtils.isNotBlank(name),"name",name);

        //queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
//    @GetMapping("/get/vo")
//    public BaseResponse<ChartVO> getChartVOById(long id, HttpServletRequest request) {
//        if (id <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        Chart Chart = ChartService.getById(id);
//        if (Chart == null) {
//            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
//        }
//        return ResultUtils.success(ChartService.getChartVO(Chart, request));
//    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param ChartQueryRequest
     * @return
     */
//    @GetMapping("/list/page")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody com.yupi.project.model.dto.Chart.ChartQueryRequest ChartQueryRequest) {
//        long current = ChartQueryRequest.getCurrent();
//        long size = ChartQueryRequest.getPageSize();
//        Page<Chart> ChartPage = ChartService.page(new Page<>(current, size),
//                getQueryWrapper(ChartQueryRequest));
//        return ResultUtils.success(ChartPage);
//    }
//
//    /**
//     * 分页获取列表（封装类）
//     *
//     * @param ChartQueryRequest
//     * @param request
//     * @return
//     */
//    @GetMapping("/list/page/vo")
//    public BaseResponse<Page<ChartVO>> listChartVOByPage(@RequestBody com.yupi.project.model.dto.Chart.ChartQueryRequest ChartQueryRequest,
//            HttpServletRequest request) {
//        long current = ChartQueryRequest.getCurrent();
//        long size = ChartQueryRequest.getPageSize();
//        // 限制爬虫
//        //ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
//        Page<Chart> ChartPage = ChartService.page(new Page<>(current, size),
//                getQueryWrapper(ChartQueryRequest));
//        return ResultUtils.success(ChartService.getChartVOPage(ChartPage, request));
//    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param ChartQueryRequest
     * @param request
     * @return
     */
//    @GetMapping("/my/list/page/vo")
//    public BaseResponse<Page<Chart>> listMyChartVOByPage(@RequestBody com.yupi.project.model.dto.Chart.ChartQueryRequest ChartQueryRequest,
//            HttpServletRequest request) {
//        if (ChartQueryRequest == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User loginUser = userService.getLoginUser(request);
//        ChartQueryRequest.setUserId(loginUser.getId());
//        long current = ChartQueryRequest.getCurrent();
//        long size = ChartQueryRequest.getPageSize();
//        // 限制爬虫
//        //ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
//        Page<Chart> ChartPage = ChartService.page(new Page<>(current, size),
//                getQueryWrapper(ChartQueryRequest));
//        return ResultUtils.success(ChartService.getChartVOPage(ChartPage, request));
//    }

    // endregion
}
